package com.dataexa.ky.core.utils;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.SneakyThrows;

import java.util.Map;
import java.util.TimeZone;

/**
 * Created by chenqixuan on 17/10/25.
 *
 * @desc json util
 */
public class JSONUtil {

    private final static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        //objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        //objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    /**
     * 将实体类转为json string
     *
     * @param object
     *
     * @return
     */
    @SneakyThrows
    public static String beanToJsonString(Object object) {
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 将实体类转为美化后的json string
     *
     * @param object
     *
     * @return
     */
    @SneakyThrows
    public static String beanToBeautifyJsonString(Object object) {
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
    }

    /**
     * 将实体类转为json string
     *
     * @param object
     *
     * @return
     */
    @SneakyThrows
    public static String beanToJsonString(
            Object object,
            boolean isBeautification
    ) {
        if (isBeautification) {
            return objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(object);
        }
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 将json转为实体类
     *
     * @param jsonString
     * @param typeReference
     *
     * @return
     */
    @SneakyThrows
    public static <T> T jsonStringToBean(
            String jsonString,
            TypeReference<T> typeReference
    ) {
        return objectMapper.readValue(jsonString, typeReference);
    }

    // 将Map转成指定的Bean
    @SneakyThrows
    public static <T> T mapToBean(
            Map map,
            Class<T> clazz
    ) {
        return objectMapper.readValue(beanToJsonString(map), clazz);
    }

    // 将Bean转成Map
    @SneakyThrows
    public static Map beanToMap(Object obj) {
        return objectMapper.readValue(beanToJsonString(obj), Map.class);
    }

    public static String test() {
        return "123";
    }
    /**
     * bean转json
     *
     * @param object
     *
     * @return
     */
    public static JsonNode beanToJson(Object object) {
        return objectMapper.convertValue(object, JsonNode.class);
    }
}